package com.minimalist.basic.config.rocketmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

/**
 * @author 11987
 */
@Slf4j
@Service
public class RocketMqProducer {
    @Autowired
    private RocketMQTemplate rocketMqTemplate;

    private final String topic = "TestTopic";

    public void sendSyncMessage(String message) {
        SendResult sendResult = rocketMqTemplate.syncSend(topic
                , MessageBuilder.withPayload(message).build());
        log.info("同步发送结果: {} {}", message, sendResult);
    }

    public void sendAsyncMessage(String message) {
        rocketMqTemplate.asyncSend(topic, MessageBuilder.withPayload(message).build()
                , new SendCallback() {

                    @Override
                    public void onSuccess(SendResult sendResult) {
                        log.info("异步发送成功: {} {}", message, sendResult);
                    }

                    @Override
                    public void onException(Throwable throwable) {
                        log.error("异步发送失败:{} {}", message, throwable.getMessage());
                    }
                });
    }

    public void sendOneWayMessage(String message) {
        rocketMqTemplate.sendOneWay(topic, MessageBuilder.withPayload(message).build());
        log.info("单向消息发送成功: {}", message);
    }

    public void sendDelayMessage(String message, int delayTime) {
        SendResult sendResult = rocketMqTemplate.syncSendDelayTimeSeconds(topic
                , MessageBuilder.withPayload(message).build(), delayTime);
        log.info("延时消息发送结果: {} {}", message, sendResult);
    }
}

